package com.mazaiting.classfile.attr.info;

import com.mazaiting.classfile.ClassReader;
import com.mazaiting.classfile.constant.ConstantPool;
import lombok.Getter;

import java.util.Arrays;

/**
 * Exceptions是变长属性，记录方法抛出的异常表
 *
 * @author mazaiting
 * @since 2021/8/12
 */
@Getter
public class ExceptionsAttribute extends AttributeInfo{
    /**
     * 异常表 无符号 u2
     */
    private int[] exceptionIndexTable;

    public ExceptionsAttribute(ConstantPool pool, int index, int length) {
        super(pool, index, length);
    }

    @Override
    public void readInfo(ClassReader reader) {
        this.exceptionIndexTable = reader.readU2UnsignedShorts();
    }

    /**
     * 获取异常数组
     * @return 异常数组
     */
    public String[] getExceptionTable() {
        String[] strings = new String[exceptionIndexTable.length];
        for (int i = 0; i < exceptionIndexTable.length; i++) {
            strings[i] = pool.getClassName(exceptionIndexTable[i]);
        }
        return strings;
    }

    @Override
    public String toString() {
        return "ExceptionsAttribute{" +
                "exceptionIndexTable=" + Arrays.toString(exceptionIndexTable) +
                '}';
    }
}
